package com.wyp168.gulimall.product.service.impl;

import com.wyp168.common.constant.ProductConstant;
import com.wyp168.common.exception.RRException;
import com.wyp168.common.to.SkuHasStockVO;
import com.wyp168.common.to.SkuReductionTO;
import com.wyp168.common.to.SpuBoundTO;
import com.wyp168.common.to.es.SkuESModel;
import com.wyp168.common.utils.FeignUtil;
import com.wyp168.common.utils.R;
import com.wyp168.gulimall.product.entity.*;
import com.wyp168.gulimall.product.feign.CouponFeignService;
import com.wyp168.gulimall.product.feign.ESClient;
import com.wyp168.gulimall.product.feign.WareFeignService;
import com.wyp168.gulimall.product.service.*;
import com.wyp168.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyp168.common.utils.PageUtils;
import com.wyp168.common.utils.Query;

import com.wyp168.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignClient;

    @Autowired
    private ESClient esClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSupInfo(SpuSaveVO spuSaveVO) {
        //1.保存spu基本信息： pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        //2.保存spu的描述图片： pms_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);
        //3.保存spu的图片集： pms_spu_images
        spuImagesService.batchSaveImages(spuInfoEntity.getId(), spuSaveVO.getImages());
        //4.保存spu的规格参数： pms_product_attr_value
        List<Baseattrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity byId = attrService.getById(baseAttr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.batchSaveProductAttrValue(productAttrValueEntities);
        //5.保存spu积分信息： gulimall-sms.sms_spu_bounds

        //TODO

        //6.保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                AtomicReference<String> defaultImage = new AtomicReference<>("");
                item.getImages().forEach(img -> {
                    for (Images image : item.getImages()) {
                        if (image.getDefaultImg() == 1) {
                            defaultImage.set(image.getImgUrl());
                        }
                    }
                });

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage.get());

//                Long skuId = skuInfoEntity.getSkuId();

                //6.1.保存sku基本信息： pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImages = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(img -> !Strings.isEmpty(img.getImgUrl())).collect(Collectors.toList());
                //6.2.保存sku的图片信息： pms_sku_images
                skuImagesService.saveBatch(skuImages);


                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //6.3.sku的销售属性信息： pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                Bounds bounds = spuSaveVO.getBounds();
                SpuBoundTO spuBoundTO = new SpuBoundTO();
                BeanUtils.copyProperties(bounds, spuBoundTO);
                spuBoundTO.setSpuId(spuInfoEntity.getId());
                //6.4.保存sku的优惠、满减信息： gulimall-sms.sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                R r1 = couponFeignService.saveSpuBounds(spuBoundTO);
                if (r1.getCode() != 0) {
                    log.error("远程保存spu积分信息失败");
                }
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    R r2 = couponFeignService.saveSkuRedicution(skuReductionTO);
                    if (r2.getCode() != 0) {
                        log.error("远程保存spu满减，打折，会员价格信息失败");
                    }
                }

            });
        }
    }

    @Override
    public void testSave(SpuInfoEntity supInfoEntity) {
        baseMapper.insert(supInfoEntity);
        log.debug("是否回传id:{}" , supInfoEntity.getId());
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(params.get("key"))) {
            queryWrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(params.get("brandId"))) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(params.get("catelogId"))) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(params.get("status"))) {
            queryWrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查询当前spuId对应的所有sku信息，包含品牌名称
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        //查询所有商品的规格属性【可以被用来检索的规格属性】
        List<ProductAttrValueEntity> skuInfos = productAttrValueService.getSkuInfosBySpuId(spuId);
        /**
         * 这里不推荐在filter或foreach循环语句中重复查表，会造成不必要的mysql开销
         */
        //获取所有能够被快速检索的属性
        List<Long> attrIds = skuInfos.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //根据attrIds，查询Attr表，获取所有能够被快速检索的字段
        List<Long> quickSearchIds = attrService.getByAttrIds(attrIds);
        //过滤出能够被快速检索的 SKu,并封装成attrs
        List<SkuESModel.Attrs> attrs = skuInfos.stream().filter(sku -> quickSearchIds.contains(sku.getAttrId()))
                .map(sku -> {
                    SkuESModel.Attrs attr = new SkuESModel.Attrs();
                    BeanUtils.copyProperties(sku, attr);
                    return attr;
                }).collect(Collectors.toList());
        //封装成ESSkuModel
        //调用库存服务，查询该sku是否有库存【hasStock】
        List<Long> skuIds = skuInfos.stream().map(ProductAttrValueEntity::getId).collect(Collectors.toList());
        R feignResult = wareFeignClient.getSkuHasStock(skuIds);
        List<SkuHasStockVO> resultList = new ArrayList<>();
        if (0 == feignResult.getCode()) {
            resultList = FeignUtil.formatListClass(feignResult, SkuHasStockVO.class);
        } else {
            log.error("远程调用库存接口失败SpuInfoServiceImpl.up()");
            throw new RRException("系统内部异常", HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        Map<Long, Boolean> resultMap = new HashMap<>();
        System.out.println(resultList.get(0).toString() + ",type:" + resultList.get(0).getClass());
        resultList.forEach(o -> {
            System.out.println(o.toString());
            if (!Objects.isNull(o)) {
                resultMap.put(o.getSkuId(), o.getHasStock());
            }
        });
        List<SkuESModel> upProducts = skuInfoEntities.stream().map(sku -> {
            SkuESModel skuESModel = new SkuESModel();
            BeanUtils.copyProperties(sku, skuESModel);
            //skuPrice、skuImg、hasStock、hotScore、brandName、brandImg、catalogName、attrs
            skuESModel.setSkuPrice(sku.getPrice());
            skuESModel.setSkuImg(sku.getSkuDefaultImg());
            //查询品牌和分类信息
            BrandEntity brand = brandService.getById(sku.getBrandId());
            if (Objects.isNull(brand)) {
                skuESModel.setBrandName(brand.getName());
                skuESModel.setBrandImg(brand.getLogo());
            }
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            if (!Objects.isNull(category)) {
                skuESModel.setCatalogName(category.getName());
            }
            //设置检索属性
            skuESModel.setAttrs(attrs);
            //设置hasStock  是否存在库存
            if (!CollectionUtils.isEmpty(resultMap)) {
                skuESModel.setHasStock(resultMap.get(sku.getSkuId()));
            }
            //热度评分【hotScore】
            //TODO 暂时设置为0
            skuESModel.setHotScore(0L);
            return skuESModel;
        }).collect(Collectors.toList());

        //将数据同步到ES
        R esSyncResult = esClient.productStatusUp(upProducts);
        if (0 == esSyncResult.getCode()) {
            log.info("远程调用es服务，上架sku数据成功");
            //修改当前spu的状态为已上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            log.error("远程调用es服务，上架sku数据失败");
            //TODO 当调用ES服务同步sku数据失败后的重试操作
        }
    }

}